package com.nationart.backend.shiro;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

public class RedisSessionDAO extends EnterpriseCacheSessionDAO  {

	private Logger log = LoggerFactory.getLogger(RedisSessionDAO.class);
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	private final String KEY_PREFIX = "shiro_redis_session_manager:";

	private String getKey(String originalKey) {
		return KEY_PREFIX + originalKey;
	}

	@Override
	public void update(Session session) throws UnknownSessionException {
		// TODO Auto-generated method stub
		log.info("修改seesion,id=[{}]", session.getId().toString());
		try {
			redisTemplate.opsForValue().set(getKey(session.getId().toString()), session, 7, TimeUnit.DAYS);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

	@Override
	public void delete(Session session) {
		// TODO Auto-generated method stub
		log.info("删除seesion,id=[{}]", session.getId().toString());
		try {
			String key = getKey(session.getId().toString());
			redisTemplate.delete(key);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}


	@Override
	protected Serializable doCreate(Session session) {
		// TODO Auto-generated method stub
		Serializable sessionId = generateSessionId(session);
		assignSessionId(session, sessionId);
		
		log.info("创建seesion,id=[{}]", session.getId().toString());
		try {
			redisTemplate.opsForValue().set(getKey(session.getId().toString()), session, 30, TimeUnit.MINUTES);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return sessionId;

	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		// TODO Auto-generated method stub
		Session session = null;
		log.info("从redis中获取session");
		try {
			session = (Session) redisTemplate.opsForValue().get(getKey(sessionId.toString()));
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return session;
	}

	public RedisTemplate<String, Object> getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
	
	

}
